<template>
  <div>
    <!--引用表格-->
    <BasicTable @register="registerTable" :rowSelection="rowSelection" :expandedRowKeys="expandedRowKeys" rowKey="id"
      @expand="handleExpand">
      <!-- 内嵌table区域 begin -->
      <template #expandedRowRender="{ record }">
        <!-- <a-tabs tabPosition="top">
          <a-tab-pane tab="城配订单" key="cityOrder" forceRender> -->
        <!--引用表格-->
        <BasicTable ref="subTable" bordered size="middle" :loading="loading" rowKey="id" :canResize="false"
          :columns="subColumns" :dataSource="dataSource" :pagination="false" :actionColumn="actionSubColumn">
          <!--字段回显插槽-->
          <template v-slot:bodyCell="{ column, record, index, text }">
            <template v-if="column.dataIndex === 'receiptZone'">
              <!--省市区字段回显插槽-->
              {{ getAreaTextByCode(text) }}
            </template>
          </template>
          <template #productinfo="{ text, record }">
            <div>商品种数：{{ record.totalNum }}</div>
            <div>商品总数：{{ record.detailNum }}</div>
            <div>商品总金额：{{ record.totalAmount }}</div>
          </template>
          <template #receiptinfo="{ text, record }">
          
            <div>收件人：{{ record.receiptName }}</div>
            <div>手机号：{{ record.receiptPhone }}</div>
            <div>地址：{{ getAreaTextByCode(record.receiptZone) }} {{ record.receiptAddress }}
            </div>
          </template>

          <!--操作栏-->
          <template #action="{ record }">
            <TableAction :actions="getSubTableAction(record)" />
          </template>
        </BasicTable>
        <!-- </a-tab-pane>
        </a-tabs> -->
      </template>
      <!-- 内嵌table区域 end -->

      <!--操作栏-->
      <template #action="{ record }">
        <TableAction :actions="getTableAction(record)" />
      </template>
    </BasicTable>
    <!-- 表单区域 -->

    <AllModal @register="submitAuditModal" :schemas="auditFormSchema" :apiUrl="audit" :height="150"
      @success="handleSuccess" />
    <XlCustomerOrdeModal @register="registerModal" @success="handleSuccess"></XlCustomerOrdeModal>
  </div>
</template>

<script lang="ts" name="lx-xlCustomerOrde" setup>
import { ref, reactive, onMounted, unref, computed } from 'vue';
import { BasicTable, useTable, TableAction } from '/@/components/Table';
import { useListPage } from '/@/hooks/system/useListPage'
import { useModal } from '/@/components/Modal';
import { subColumns, cityClumns, citySearchSchema,auditFormSchema } from './XlCustomerOrde.data';
import { cityList, cityOrderList, shiftDelivery, audit, cityShiftDelivery1 } from './XlCustomerOrde.api';
import { useUserStore } from '/@/store/modules/user';
import { getAreaTextByCode } from '/@/components/Form/src/utils/Area';
import { useMessage } from "/@/hooks/web/useMessage";
import XlCustomerOrdeModal from './components/XlCustomerOrdeModal.vue'
import AllModal from './components/AllModal.vue';

const { createConfirm, createMessage } = useMessage();
const queryParam = reactive<any>({});
const checkedKeys = ref<Array<string | number>>([]);
const userStore = useUserStore();
// 展开key
const expandedRowKeys = ref<any[]>([]);
const subTable = ref(); //表格对象
const loading = ref(false);
const dataSource = ref([]);


//注册model
const [registerModal, { openModal }] = useModal();
const [submitAuditModal, submitAuditUseModal] = useModal();

//子表操作列
const actionSubColumn = ref({
      width: 120,
      title: '操作',
      dataIndex: 'action',
      slots: { customRender: 'action' },
      fixed: undefined,
})

//注册table数据
const { prefixCls, tableContext, onExportXls, onImportXls } = useListPage({
  tableProps: {
    // title: '城配审核',
    api: cityList,
    columns: cityClumns,
    canResize: false,
    pagination: false,
    formConfig: {
      schemas: citySearchSchema,
      autoSubmitOnEnter: true,
      showAdvancedButton: true,
      fieldMapToNumber: [
      ],
    },
    actionColumn: {
      width: 180,
      title: '操作',
      dataIndex: 'action',
      slots: { customRender: 'action' },
      fixed: undefined,
    },
    beforeFetch: (params) => {
      return Object.assign(params, queryParam);
    },
  },
})

const [registerTable, { reload }, { rowSelection, selectedRowKeys, selectedRows }] = tableContext


function loadSubData(city) {
  dataSource.value = []
  loading.value = true
  ///xl/xlCustomerOrde/cityList
  cityOrderList({ city: city }).then((res) => {
    dataSource.value = res
  }).finally(() => {
    loading.value = false
  })
}

/**
 * 展开事件
 * */
function handleExpand(expanded, record) {
  expandedRowKeys.value = [];
  dataSource.value = [];
  if (expanded === true) {
    expandedRowKeys.value.push(record.id);
    loadSubData(record.city);
  }
}

/**
 * 详情
*/
function handleDetail(record: Recordable) {
  openModal(true, {
    record,
    isUpdate: true,
    showFooter: false,
  });
}

/**
 * 转一件代发
 */
 async function handleShiftDelivery(record) {
    //一件代发审核
    submitAuditUseModal.openModal(true, {
      title: '一件代发审核',
      record: { 
        id: record?.id,
        deliveryWay: '2', //转为快递发货
       },
    });
  handleSuccess()
}
/**
 * 整个城市转一件代发，并审核通过
 */
async function handleCityShiftDelivery(record) {
  
  createConfirm({
    iconType: 'warning',
    title: '城市订单转一件代发确认',
    content: '确认将此城市的订单都转为一件代发，并自动审核通过？',
    okText: '确认',
    cancelText: '取消',
    onOk: async () => {
      console.log(record);
      console.log(record.city);
      
      cityShiftDelivery1({ city: record.city }, handleSuccess);
      return;
    },
    onCancel: async () => {

      return;
    }
  });
}
/**
 * 城配审核
 */
 async function handleCityAudit(record) {
  if (!record.sumAmount){
    createMessage.warning('当前城市没有要审核的订单！')
  }

  //判断订单金额是否达标
  if (record?.sumAmount < record?.baseAmount) {
    createConfirm({
      iconType: 'warning',
      title: '城配订单批量审核确认',
      content: '此批次城配订单未达到城市金额起订量，是否进行审核',
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        //达标直接审核
        submitAuditUseModal.openModal(true, {
          title: '城配订单审核',
          record: { city: record?.city },
        });
        return;
      }
    });
  } else {
    //达标直接审核
    submitAuditUseModal.openModal(true, {
      title: '城配订单审核',
      record: { city: record?.city },
    });
  }
}

/**
 * 成功回调
 */
function handleSuccess() {
  (selectedRowKeys.value = []) && reload();
  expandedRowKeys.value = [];
  dataSource.value = [];
}
/**
   * 操作栏
   */
function getTableAction(record) {
  return [
    {
      label: '审核确认',
      onClick: handleCityAudit.bind(null, record),
      auth: 'lx:xl_customer_orde:audit'
    },
    {
      label: '转一件代发',
      onClick: handleCityShiftDelivery.bind(null, record),
      auth: 'lx:xl_customer_orde:audit'
    },
  ]
}


/**
   * 操作栏
   */
function getSubTableAction(record) {
  return [
    {
      label: '详情',
      onClick: handleDetail.bind(null, record),
    },
    {
      label: '转一件代发',
      onClick: handleShiftDelivery.bind(null, record),
      auth: 'lx:xl_customer_orde:shiftDelivery'
    },
  ]
}

</script>

<style lang="less" scoped>
:deep(.ant-picker),
:deep(.ant-input-number) {
  width: 100%;
}
</style>
